package org.vserver.security;

import org.apache.log4j.Logger;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;
import org.vserver.dao.UserDao;
import org.vserver.entity.User;

import java.util.List;

/**
 * User: karpden ( Denis Karpov )
 * Date: 4/4/11
 * Time: 7:23 PM
 */
@Name("authenticator")
public class Authenticator {
    private final Logger log = Logger.getLogger(Authenticator.class);
    @In
    Credentials credentials;
    @In
    Identity identity;
    @In("#{UserDao}")
    UserDao userDao;

    public boolean authenticate() {
        log.info("UUU "+credentials.getUsername() );
        User user = userDao.getUser(credentials.getUsername());
        if (user!=null) {
//        if (userDao.checkPwd(user,credentials.getPassword())){
            List<String> roles = userDao.getUserRoles(user);
            user.setRoles(roles);
            for (String role : roles){
                identity.addRole(role);
            }
            log.info("UUU2 "+user.toString() );
            userDao.setCurrentUser(user);
            return true;
        }
        return false;
    }
}
